package com.yanh.auth.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.yanh.auth.entity.MemberEntity;
import com.yanh.auth.entity.MemberReceiveAddressEntity;
import com.yanh.auth.service.MemberReceiveAddressService;
import com.yanh.auth.service.MemberService;
import com.yanh.auth.vo.SocialUser;
import com.yanh.auth.vo.UserLoginVo;
import com.yanh.auth.vo.UserRegisterVo;
import com.yanh.jcommon.advice.ResultCode;
import com.yanh.jcommon.constant.AuthServerConstant;
import com.yanh.jcommon.utils.HttpUtils;
import com.yanh.jcommon.utils.R;
import com.yanh.jcommon.vo.member.MemberResponseVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.yanh.jcommon.constant.AuthServerConstant.LOGIN_USER;

/**
 * @Description:
 * @Created:
 * @author:
 * @createTime:
 **/

@Tag(name="登入注册接口",description = "登入注册接口")
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberReceiveAddressService memberReceiveAddressService;

    @Operation(summary = "发送验证码",description = "发送验证码")
    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) throws Exception {

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000) {
                //60s内不能再发
                return R.error(ResultCode.SMS_CODE_EXCEPTION.getCode(),ResultCode.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();

        //存入redis，防止同一个手机号在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
                redisStorage,10, TimeUnit.MINUTES);
        sendCode(phone,codeNum);
        return R.ok();
    }

    private void sendCode(String phone,String code) throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI4Fzjg1d4vtpS3uKHUZ8B")
                .setAccessKeySecret("tpjRAwo98TKUih7T2UGlCWmPp7Il3g");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("漫玩")
                .setTemplateCode("SMS_192821653")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse resp =client.sendSms(sendSmsRequest);
    }

    @Operation(summary = "用户注册",description = "用户注册")
    @PostMapping(value = "/register")
    public String register(@Validated @RequestBody UserRegisterVo vos) {
        //1、效验验证码
        String code = vos.getCode();
        //获取存入Redis里的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R register = memberService.register(vos);
                if (register.getCode() == 0) {
                    return "用户注册成功";
                } else {
                    return "用户注册失败";
                }


            } else {
                return "验证码错误";
            }
        } else {
            return "验证码错误";
        }
    }

    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://jmall.com";
        }
    }

    @Operation(summary = "用户登入",description = "用户登入")
    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, HttpSession session
    ) {
        MemberEntity login = memberService.login(vo);
        MemberResponseVo memberResponseVo=new MemberResponseVo();
        memberResponseVo.setId(login.getId());
        memberResponseVo.setNickname(login.getNickname());
        if (memberResponseVo!=null) {
            session.setAttribute(LOGIN_USER,memberResponseVo);
            return "redirect:http://jmall.com";
//            return "用户登入成功";

        } else {
            return "用户登入失败";
        }
    }

    @Operation(summary = "获取gitnee登入地址",description = "获取gitnee登入地址")
    @GetMapping(value = "/oauth2.0/gitnee/url")
    public String getGitneeUrl() {
        return "https://gitee.com/oauth/authorize?client_id=c9de5765452c5ad0d4bbbeda2be7f9d7cecabd271fbf39c7617762159fd39166&redirect_uri=http://jmall.com/api/auth/oauth2.0/gitnee/success&response_type=code";
    }

    @Operation(summary = "gitnee回调地址",description = "gitnee回调地址")
    @GetMapping(value = "/oauth2.0/gitnee/success")
    public String logincode(@RequestParam("code") String code, HttpSession session) throws Exception {

        System.out.print(code);
        Map<String, String> map = new HashMap<>();
        map.put("client_id","c9de5765452c5ad0d4bbbeda2be7f9d7cecabd271fbf39c7617762159fd39166");
        map.put("client_secret","9b01f8894aae329dc286dfcedb7e37b40d85953717f860cc4a8ed89e997a420e");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://jmall.com/api/auth/oauth2.0/gitnee/success");
        map.put("code",code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了access_token,转为通用社交登录对象
            String json = EntityUtils.toString(response.getEntity());
            System.out.print(json);
            //String json = JSON.toJSONString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //登录或者注册这个社交用户
            System.out.println(socialUser.getAccess_token());
            MemberEntity oauthLogin = memberService.login(socialUser);
            if (oauthLogin!=null) {
                session.setAttribute(LOGIN_USER,oauthLogin);
                return "登入成功";
            } else {

                return "登入失败";
            }

        } else {
            return "登入失败";
        }
    }


    /**
     * 根据会员id查询会员的所有地址
     * @param memberId
     * @return
     */
    @GetMapping(value = "/{memberId}/address")
    public List<MemberReceiveAddressEntity> getAddress(@PathVariable("memberId") Long memberId) {

        List<MemberReceiveAddressEntity> addressList = memberReceiveAddressService.getAddress(memberId);

        return addressList;
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        MemberReceiveAddressEntity memberReceiveAddress = memberReceiveAddressService.getById(id);
        return R.ok().put("memberReceiveAddress", memberReceiveAddress);
    }

}
